import { getUserInfoApi, loginApi } from "@/api/user"
import { setToken, getToken, removeToken } from "@/utils/auth"

const state = () => ({
  token: getToken(),
  userInfo: {}
})

const mutations = {
  // 设置token
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  // 移除token
  removeToken(state) {
    state.token = null
    removeToken
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
}

const actions = {
  // 登录操作
  async loginAction(context, payload) {
    let res = await loginApi(payload)
    // console.log(res)
    // 设置token
    context.commit('setToken', res.token)
  },
  async getUserProfileAction(context) {
    let res = await getUserInfoApi()
    // console.log(res)
    context.commit('setUserInfo', res.userInfo)
  },
  // 退出操作
  async logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
